// 防抖工具函数
export function debounce<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let timeoutId: NodeJS.Timeout;
  
  return (...args: Parameters<T>) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => func(...args), delay);
  };
}

// 节流工具函数
export function throttle<T extends (...args: any[]) => any>(
  func: T,
  delay: number
): (...args: Parameters<T>) => void {
  let lastCall = 0;
  
  return (...args: Parameters<T>) => {
    const now = Date.now();
    if (now - lastCall >= delay) {
      lastCall = now;
      func(...args);
    }
  };
}

// 防重复请求工具
class RequestQueue {
  private pendingRequests = new Map<string, Promise<any>>();

  async execute<T>(key: string, requestFn: () => Promise<T>): Promise<T> {
    // 如果已有相同请求在进行中，返回该请求的Promise
    if (this.pendingRequests.has(key)) {
      return this.pendingRequests.get(key) as Promise<T>;
    }

    // 创建新请求
    const promise = requestFn().finally(() => {
      // 请求完成后从队列中移除
      this.pendingRequests.delete(key);
    });

    this.pendingRequests.set(key, promise);
    return promise;
  }

  // 取消待处理的请求
  cancel(key: string): boolean {
    return this.pendingRequests.delete(key);
  }

  // 清空所有待处理请求
  clear(): void {
    this.pendingRequests.clear();
  }
}

// 创建全局请求队列实例
export const requestQueue = new RequestQueue();